//
//  SplashViewController.m
//  Main
//
//  Created by Fanty on 13-12-18.
//  Copyright (c) 2013年 Fanty. All rights reserved.
//

#import "SplashViewController.h"
#import "IsolatedStorageFile.h"
#import "Zilla.h"
#import "ZillaAccessData.h"
#import "Modules.h"
#import "DataCenter.h"
#import "CApplication.h"
#import "KKProgressToolbar.h"
#import "BSLCubeConstant.h"
#import "CubeModuleManager.h"
#import "CubeViewController.h"

#import "AsyncRequestWorkGroup.h"


#define NOTPROMISS      1
#define SERVER_ERROR    2
#define APP_UPDATE      3
#define MODULE_RETRY    7
#define ROLE_PRIVILIGES 5
#define ALERT_ENTER 6


@interface CubeSplashViewController ()<ZillaDelegate,UIAlertViewDelegate,KKProgressToolbarDelegate>
{
    BOOL disMissAlert_firstTime;
    UIImageView* imgView;
    UIActivityIndicatorView* loadingView;

}
//复制www 目录去指定根
-(void)wwwCheckAndCopy;

//检测版本更新
-(void)checkVersionDownloaded;

//跳转主页
-(void)redirectMainPage;
//检查模块更新信息
- (void)checkMoudles;
@end

@implementation CubeSplashViewController

-(id)init{
    self=[super init];
    if(self){
        zillaSDK=[[Zilla alloc] initWithZillAccessData:[ZillaAccessData activeSession]];
        zillaSDK.delegate=self;
    }
    
    return self;
}

- (void)viewDidLoad{
    [super viewDidLoad];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeviceOrientationDidChange:)name:UIDeviceOrientationDidChangeNotification object:nil];
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
     imgView=[[UIImageView alloc] initWithFrame:self.view.bounds];
    imgView.contentMode=UIViewContentModeScaleAspectFit;
    imgView.image=[self getImageName];
    [self.view addSubview:imgView];
    
     loadingView=[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    loadingView.frame=CGRectMake(0.0f, 0.0f, 64.0f, 64.0f);
    loadingView.center=self.view.center;
    [self.view addSubview:loadingView];
    [loadingView startAnimating];
    
    statusToolbar = [[KKProgressToolbar alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-44.0f, self.view.bounds.size.width, 44.0f)];
    statusToolbar.autoresizingMask=UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth;
    statusToolbar.actionDelegate = self;
    [self.view addSubview:statusToolbar];
    
    [self wwwCheckAndCopy];
}
- (void)handleDeviceOrientationDidChange:(UIInterfaceOrientation)interfaceOrientation
{
    imgView.image = [self getImageName];
    imgView.frame= self.view.frame;
    loadingView.center = self.view.center;
}
- (UIImage*)getImageName{
    NSDictionary *dicImgV = @{@"320x480" : @"LaunchImage-700",@"480x320" : @"LaunchImage-700", @"320x568" : @"LaunchImage-700-568h",@"568x320" : @"LaunchImage-700-568h", @"375x667" : @"LaunchImage-800-667h",@"667x375":@"LaunchImage-800-667h", @"414x736" : @"LaunchImage-800-Portrait-736h",@"736x414":@"LaunchImage-800-Landscape-736h",@"768x1024":@"LaunchImage-700-Portrait",@"568x320":@"LaunchImage-700-Portrait-568h",@"750x1134":@"LaunchImage-800-667h",@"1242x2208":@"LaunchImage-800-Portrait-736h",@"2048x1536":@"LaunchImage-700-Landscape",@"1024x768":@"LaunchImage-700-Landscape~ipad",@"LaunchImage-700-Portrait":@"1536x2048"};
    NSString * key = [NSString stringWithFormat:@"%dx%d", (int)[UIScreen mainScreen].bounds.size.width, (int)[UIScreen mainScreen].bounds.size.height];
    return  [UIImage imageNamed:dicImgV[key]];
    
}
- (void)didReceiveMemoryWarning{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];
}


-(void)wwwCheckAndCopy{
    
    if([[DataCenter defaultCenter].installMoudules count]<1)
        [[CApplication sharedApplication].cubeModuleManager loadLocalModuleList:YES];
    if ([DataCenter defaultCenter].serviceModules.count <1) {
        [[CApplication sharedApplication].cubeModuleManager loadLocalModuleList:NO];
    }
    __weak Zilla* __zillaSDK=zillaSDK;
    
    statusToolbar.statusLabel.text =@"正在检测基础组件";
    
    dispatch_async(dispatch_get_global_queue(0,0), ^{
        
        
        NSUserDefaults* userDefault=[NSUserDefaults standardUserDefaults];
        NSString* appVersion=[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        
        NSString* standardVersion=[userDefault objectForKey:@"savedVersion"];
        
        //如果安装的app版本与已有版本不一致
        if(![appVersion isEqualToString:standardVersion]){
            
            [IsolatedStorageFile copyFolderAtPath:[IsolatedStorageFile cordovaResourceDirectory] toPath:[IsolatedStorageFile cordovaRootDirectory] error:nil];
            
            NSDictionary* mainDictonary = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"mainModule" ofType:@"json"]] options:kNilOptions error:nil];
            
            NSString* mainIdentifier=[mainDictonary objectForKey:@"mainModuleTag"];
            
            NSArray* list=[mainDictonary objectForKey:@"list"];
            
            for(NSDictionary* dict in list){
                NSString* identifier=[dict objectForKey:@"identifier"];
                CubeModel* mainModel=[[DataCenter defaultCenter] finidInstallCubeModule:identifier];
                if(mainModel==nil){  //没有安装主模块
                    mainModel=[[CubeModel alloc] init];
                    [[DataCenter defaultCenter].installMoudules addObject:mainModel];
                }
                mainModel.mainModule=([identifier isEqualToString:mainIdentifier]);
                mainModel.build=[[dict objectForKey:@"build"] intValue];
                mainModel.version=[dict objectForKey:@"version"];
                mainModel.iconUrl=[dict objectForKey:@"iconUrl"];
                mainModel.name=[dict objectForKey:@"name"];
                mainModel.identifier=identifier;
                mainModel.releaseNote=[dict objectForKey:@"releaseNote"];
                mainModel.platform=[dict objectForKey:@"platform"];
                mainModel.moduleUrl=[dict objectForKey:@"moduleUrl"];
                mainModel.moduleType=CubeMoudleStatusFinish;
            }
            [NSKeyedArchiver archiveRootObject:[DataCenter defaultCenter].installMoudules toFile:[IsolatedStorageFile moudlelistDirectory]];
            
            [userDefault setObject:appVersion forKey:@"savedVersion"];
            [userDefault synchronize];
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [__zillaSDK checkAppVaildate];
        });
        
    });
}

-(void)checkVersionDownloaded{
    statusToolbar.statusLabel.text =@"正在检测应用更新";
    [zillaSDK checkAppVersion];
}
//检查模块更新信息
- (void)checkMoudles{
    statusToolbar.statusLabel.text =@"正在检测基础模块";
    [[CApplication sharedApplication].cubeModuleManager loadLocalModuleList:YES];
    [zillaSDK syncModules];

}
-(void)syncModulesSuccess:(CubeModelList*)remoteServiceList{
    
    modelList=remoteServiceList;
    DataCenter* dataCenter=[DataCenter defaultCenter];
    
    //本地的service模块全部替换成最新模块
    if([modelList.modules count]>0){
        dataCenter.serviceModules = modelList.modules;
        [[CApplication sharedApplication].cubeModuleManager syncModuleList:modelList.modules];
    }
    [self redirectMainPage];
}

-(void)redirectMainPage{
    if([[DataCenter defaultCenter].installMoudules count]>0){
        
        CubeViewController* controller=[[CubeViewController alloc] init];
        
        NSArray* installMoudules=[DataCenter defaultCenter].installMoudules;
            CubeModel* cubeModel=[installMoudules firstObject];
        for(CubeModel* __cubeModel in installMoudules){
            if(__cubeModel.mainModule){
                cubeModel=__cubeModel;
                break;
            }
        }
        [controller loadFilePageWithFileUrl:[NSURL fileURLWithPath:[[IsolatedStorageFile cubeModuleIdentifierRoot:cubeModel.identifier] stringByAppendingPathComponent:@"index.html"]]];
        [self.navigationController pushViewController:controller animated:YES];
    }
    else{
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"你暂未有最新模块， 请从服务器上配置好！" message:nil delegate:self cancelButtonTitle:@"关闭应用" otherButtonTitles:nil, nil];
        alertView.tag=NOTPROMISS;
        [alertView show];
    }
}



#pragma mark zilla delegate

//应用验证成功
-(void)authorSuccess{
    //开始检测应用版本
    [self checkVersionDownloaded];
}

//应用验证失败
-(void)authorFailed:(int)statusCode errorMessage:(NSString *)errorMessage{
    
    if(statusCode==403 || statusCode==400 || statusCode==520){
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:errorMessage message:nil delegate:self cancelButtonTitle:@"退出" otherButtonTitles:nil, nil];
        alertView.tag=NOTPROMISS;
        [alertView show];
    }
    else{
        UIAlertView* alertView=[[UIAlertView alloc] initWithTitle:@"网络异常，请检查网络" message:nil delegate:self cancelButtonTitle:@"关闭" otherButtonTitles:nil, nil];
        alertView.tag=SERVER_ERROR;
        [alertView show];
        disMissAlert_firstTime = YES;
      [self performSelector:@selector(disMissAlertView:) withObject:alertView afterDelay:2];
    }
}
- (void)disMissAlertView:(UIAlertView*)alertView{
    [alertView dismissWithClickedButtonIndex:0 animated:YES];
    if (disMissAlert_firstTime) {
        [self redirectMainPage];
    }
}
-(void)syncVersionFinish:(CubeModelList*)remoteServiceList{
    
    modelList=remoteServiceList;
int newBuild = modelList.build;
    int currentBuild = [[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleVersion"] intValue];
    if (newBuild > currentBuild){
        NSString *currentVersion = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleShortVersionString"];
        NSString *message = [NSString stringWithFormat:@"当前版本:%@\n最新版本:%@\n版本说明:\n%@", currentVersion, modelList.version, [modelList.releaseNote length]>0?modelList.releaseNote:@""];
        
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[ NSString stringWithFormat:@"%@平台版本更新",[[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleDisplayName"] ] message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"更新", nil];
        alertView.tag=APP_UPDATE;
        [alertView show];
    }
    else{
        //开始检测模块
        [self checkMoudles];
    }


}

#pragma mark alertview delegate
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag== SERVER_ERROR){
        
//        if(buttonIndex==1){
//            [zillaSDK checkAppVaildate];
//        }
//        else{
//      }
        if (!disMissAlert_firstTime) {
            [self redirectMainPage];
        }
    }
    else if(alertView.tag==APP_UPDATE){
        if(buttonIndex==1){
            //版本更新
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:modelList.appUrl]];
            exit(0);
        }
        else{
            //开始检测模块
            [self redirectMainPage];
        }
    }
    else if(alertView.tag==ALERT_ENTER){
        [self redirectMainPage];
    }
    else if(alertView.tag==NOTPROMISS){
        exit(0);
    }
}







@end





